<template>
    <div class="training-history-page">
        <van-nav-bar title="Training History" left-text="Back" left-arrow @click-left="$router.back()" />

        <!-- Stats Overview -->
        <div class="stats-overview">
            <div class="stat-card">
                <div class="stat-number">{{ totalSessions }}</div>
                <div class="stat-label">Total Sessions</div>
            </div>
            <div class="stat-card">
                <div class="stat-number">{{ totalHours }}h</div>
                <div class="stat-label">Practice Time</div>
            </div>
            <div class="stat-card">
                <div class="stat-number">{{ averageScore }}%</div>
                <div class="stat-label">Avg Score</div>
            </div>
        </div>

        <!-- Filter Tabs -->
        <van-tabs v-model:active="activeTab" sticky>
            <van-tab title="All" name="all">
                <div class="history-list">
                    <div v-for="session in filteredSessions" :key="session.id" class="session-item"
                        @click="viewSession(session)">
                        <div class="session-header">
                            <div class="session-info">
                                <h3 class="session-title">{{ session.scenario }}</h3>
                                <div class="session-meta">
                                    <span class="session-character">with {{ session.character }}</span>
                                    <span class="session-date">{{ formatDate(session.date) }}</span>
                                </div>
                            </div>
                            <div class="session-score" :class="getScoreClass(session.score)">
                                {{ session.score }}%
                            </div>
                        </div>

                        <div class="session-details">
                            <div class="detail-item">
                                <van-icon name="clock-o" />
                                <span>{{ session.duration }} min</span>
                            </div>
                            <div class="detail-item">
                                <van-icon name="chat-o" />
                                <span>{{ session.messages }} messages</span>
                            </div>
                            <div class="detail-item">
                                <van-icon name="star-o" />
                                <span>{{ session.skills.join(', ') }}</span>
                            </div>
                        </div>

                        <div v-if="session.feedback" class="session-feedback">
                            <div class="feedback-title">Key Feedback:</div>
                            <div class="feedback-text">{{ session.feedback }}</div>
                        </div>
                    </div>
                </div>
            </van-tab>

            <van-tab title="Recent" name="recent">
                <div class="history-list">
                    <div v-for="session in recentSessions" :key="session.id" class="session-item"
                        @click="viewSession(session)">
                        <div class="session-header">
                            <div class="session-info">
                                <h3 class="session-title">{{ session.scenario }}</h3>
                                <div class="session-meta">
                                    <span class="session-character">with {{ session.character }}</span>
                                    <span class="session-date">{{ formatDate(session.date) }}</span>
                                </div>
                            </div>
                            <div class="session-score" :class="getScoreClass(session.score)">
                                {{ session.score }}%
                            </div>
                        </div>
                    </div>
                </div>
            </van-tab>

            <van-tab title="Best" name="best">
                <div class="history-list">
                    <div v-for="session in bestSessions" :key="session.id" class="session-item"
                        @click="viewSession(session)">
                        <div class="session-header">
                            <div class="session-info">
                                <h3 class="session-title">{{ session.scenario }}</h3>
                                <div class="session-meta">
                                    <span class="session-character">with {{ session.character }}</span>
                                    <span class="session-date">{{ formatDate(session.date) }}</span>
                                </div>
                            </div>
                            <div class="session-score" :class="getScoreClass(session.score)">
                                {{ session.score }}%
                            </div>
                        </div>
                    </div>
                </div>
            </van-tab>
        </van-tabs>

        <!-- Empty State -->
        <div v-if="filteredSessions.length === 0" class="empty-state">
            <van-empty description="No training sessions yet">
                <van-button type="primary" size="small" @click="startTraining">
                    Start Your First Session
                </van-button>
            </van-empty>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'

const router = useRouter()
const activeTab = ref('all')

interface TrainingSession {
    id: string
    scenario: string
    character: string
    date: number
    duration: number
    messages: number
    score: number
    skills: string[]
    feedback?: string
}

const sessions = ref<TrainingSession[]>([
    {
        id: '1',
        scenario: 'Job Interview - Software Developer',
        character: 'Sarah Chen',
        date: Date.now() - 2 * 24 * 60 * 60 * 1000,
        duration: 15,
        messages: 24,
        score: 85,
        skills: ['Communication', 'Confidence'],
        feedback: 'Great technical explanations, work on maintaining eye contact'
    },
    {
        id: '2',
        scenario: 'Networking Event',
        character: 'Marcus Johnson',
        date: Date.now() - 5 * 24 * 60 * 60 * 1000,
        duration: 12,
        messages: 18,
        score: 92,
        skills: ['Social Skills', 'Networking'],
        feedback: 'Excellent conversation flow and natural transitions'
    },
    {
        id: '3',
        scenario: 'Team Meeting Presentation',
        character: 'Lisa Wang',
        date: Date.now() - 7 * 24 * 60 * 60 * 1000,
        duration: 20,
        messages: 32,
        score: 78,
        skills: ['Presentation', 'Leadership'],
        feedback: 'Clear structure, could improve on handling interruptions'
    },
    {
        id: '4',
        scenario: 'Customer Service Call',
        character: 'David Miller',
        date: Date.now() - 10 * 24 * 60 * 60 * 1000,
        duration: 8,
        messages: 15,
        score: 88,
        skills: ['Empathy', 'Problem Solving']
    }
])

const totalSessions = computed(() => sessions.value.length)
const totalHours = computed(() => {
    return Math.round(sessions.value.reduce((sum, session) => sum + session.duration, 0) / 60 * 10) / 10
})
const averageScore = computed(() => {
    if (sessions.value.length === 0) return 0
    return Math.round(sessions.value.reduce((sum, session) => sum + session.score, 0) / sessions.value.length)
})

const filteredSessions = computed(() => {
    switch (activeTab.value) {
        case 'recent':
            return recentSessions.value
        case 'best':
            return bestSessions.value
        default:
            return sessions.value
    }
})

const recentSessions = computed(() => {
    return sessions.value
        .slice()
        .sort((a, b) => b.date - a.date)
        .slice(0, 5)
})

const bestSessions = computed(() => {
    return sessions.value
        .slice()
        .sort((a, b) => b.score - a.score)
        .slice(0, 5)
})

const getScoreClass = (score: number) => {
    if (score >= 90) return 'score-excellent'
    if (score >= 80) return 'score-good'
    if (score >= 70) return 'score-average'
    return 'score-needs-improvement'
}

const formatDate = (timestamp: number) => {
    const now = Date.now()
    const diff = now - timestamp
    const days = Math.floor(diff / (1000 * 60 * 60 * 24))

    if (days === 0) {
        return 'Today'
    } else if (days === 1) {
        return 'Yesterday'
    } else if (days < 7) {
        return `${days} days ago`
    } else {
        return new Date(timestamp).toLocaleDateString()
    }
}

const viewSession = (session: TrainingSession) => {
    router.push(`/training/session/${session.id}`)
}

const startTraining = () => {
    router.push('/training')
}
</script>

<style lang="scss" scoped>
.training-history-page {
    min-height: 100vh;
    background: #f8f9fa;
}

.stats-overview {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 12px;
    padding: 16px;
    margin-bottom: 8px;

    .stat-card {
        background: white;
        border-radius: 12px;
        padding: 16px;
        text-align: center;

        .stat-number {
            font-size: 24px;
            font-weight: 600;
            color: #323233;
            margin-bottom: 4px;
        }

        .stat-label {
            font-size: 12px;
            color: #969799;
        }
    }
}

.history-list {
    padding: 0 16px 16px;

    .session-item {
        background: white;
        border-radius: 12px;
        padding: 16px;
        margin-bottom: 12px;
        cursor: pointer;
        transition: all 0.3s ease;

        &:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
        }

        .session-header {
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            margin-bottom: 12px;

            .session-info {
                flex: 1;

                .session-title {
                    font-size: 16px;
                    font-weight: 600;
                    color: #323233;
                    margin: 0 0 4px 0;
                }

                .session-meta {
                    display: flex;
                    flex-direction: column;
                    gap: 2px;

                    .session-character {
                        font-size: 14px;
                        color: #646566;
                    }

                    .session-date {
                        font-size: 12px;
                        color: #969799;
                    }
                }
            }

            .session-score {
                font-size: 18px;
                font-weight: 600;
                padding: 4px 8px;
                border-radius: 8px;

                &.score-excellent {
                    color: #07c160;
                    background: #f0f9ff;
                }

                &.score-good {
                    color: #1989fa;
                    background: #e6f7ff;
                }

                &.score-average {
                    color: #ff976a;
                    background: #fff7e6;
                }

                &.score-needs-improvement {
                    color: #ee0a24;
                    background: #fff1f0;
                }
            }
        }

        .session-details {
            display: flex;
            gap: 16px;
            margin-bottom: 12px;

            .detail-item {
                display: flex;
                align-items: center;
                gap: 4px;
                font-size: 12px;
                color: #969799;

                .van-icon {
                    font-size: 14px;
                }
            }
        }

        .session-feedback {
            .feedback-title {
                font-size: 12px;
                font-weight: 500;
                color: #323233;
                margin-bottom: 4px;
            }

            .feedback-text {
                font-size: 14px;
                color: #646566;
                line-height: 1.4;
            }
        }
    }
}

.empty-state {
    padding: 40px 16px;
}

:deep(.van-tabs__nav) {
    background: white;
}

:deep(.van-tabs__content) {
    background: #f8f9fa;
}
</style>